<!-- 我的学社组件 -->
<template>
  <view>
    <view v-if="societyNum <= 1" class="mb-1 text-40 c-#333 font-bold">我的学社</view>
    <!-- 未加入 -->
    <view v-if="societyNum == 0 || !userStore.isLogin"
      class="shadow-card rounded-md bg-white w-full h-560 flex flex-col justify-center items-center"
      @click="onCreateSociety">
      <u-image width="120" height="120" src="/static/images/home/ic_add.png"></u-image>
      <view class="w-280 mt-5 text-center text-28 c-#33">创建你的专属外贸学社 打造私密学习空间</view>
    </view>
    <!-- 已加入单个 -->
    <view v-if="societyNum == 1 && userStore.isLogin" class="relative shadow-card rounded-md bg-white w-full h-696 py-3">
      <view class="px-4">
        <!-- 标签 已过期 优先级最高 全员可见 -->
        <view v-if="data[0].club.status == 4"
          class="absolute top-9 right-0 w-118 h-40 rounded-l-sm flex items-center justify-center bg-#FF513A">
          <view class="text-24 c-white ml-1">已过期</view>
        </view>
        <view v-else>
          <!-- 社长 / 非社长 -->
          <!-- 标签 非正常状态 -->
          <!-- 标签 非正常状态 -->
          <view v-if="data[0].club.status != 1 || data[0].audit_status != 1"
            class="absolute top-9 right-0 w-118 h-40 rounded-l-sm flex items-center justify-center"
            :class="[societyTagType === 'warming' ? 'bg-#F4AF22' : 'bg-#FF513A']">
            <view class="text-24 c-white ml-1">{{ societyTagLabel }}</view>
          </view>
          <!-- 标签 正常状态且为社长vip距过期30天 社长非顾问身份 -->
          <view
            v-if="data[0].club.status == 1 && data[0].member_position == 3 && data[0].creator.identity != 1 && onValidityRange(data[0].creator.vip_validity)"
            class="absolute top-9 right-0 w-118 h-40 rounded-l-sm flex items-center justify-center bg-#F4AF22">
            <u-image width="28" height="28" src="/static/images/home/ic_clock.png"></u-image>
            <view class="text-24 c-white ml-1">{{ onCountDown(data[0].creator.vip_validity) }}天</view>
          </view>
        </view>
        <view class="c-#333 text-28 mb-1">{{ data[0]?.club?.club_name }}</view>
        <u-image border-radius="12" width="100%" height="416" :src="data[0]?.club?.cover_image"
          @click="enterSociety('/package_society/pages/society/index?tabId=0', data[0]?.club_id, data[0])"></u-image>
        <view class="flex items-center mt-2">
          <view class="flex relative w-80 h-32">
            <view v-for="(item, index) in data[0]?.avatar_info" :key="index" class="rounded-full bg-#808080 border-avatar"
              :style="{ 'position': 'absolute', 'left': (index * 16) + 'rpx', 'z-index': 10 - index }">
              <u-image shape="circle" width="32" height="32"
                :src="item?.user?.avatar ?? '/static/images/user/ic_def_avatar.png'"></u-image>
            </view>
          </view>
          <view class="c-#B5B5B5 text-24 ml-2 text-single">创建人：{{ data[0]?.creator?.nickname }}</view>
          <view class="w-2 h-22 bg-#B5B5B5 mx-2" />
          <view class="flex-shrink-0 c-#B5B5B5 text-24">成员：{{ data[0]?.club?.member_number }}</view>
        </view>
        <view class="h-2 w-full bg-#E5E5E5 mt-3 mb-4" />
      </view>
      <view class="flex">
        <view v-for="(item, index) in societyOptions" :key="index" class="w-20% flex flex-col items-center"
          @click="enterSociety(item.url, data[0]?.club_id, data[0])">
          <view class="relative">
            <u-image mode="aspectFit" width="36" height="36" :src="item.icon"></u-image>
            <u-badge v-if="item.id == 1 && item.notice && item.question_unread" :is-dot="true" :offset="[-8, -8]"
              type="error"></u-badge>
            <u-badge v-if="item.id == 2 && item.notice && item.service_unread" :is-dot="true" :offset="[-8, -8]"
              type="error"></u-badge>
            <u-badge v-if="item.id == 4 && item.notice && item.member_unread" :is-dot="true" :offset="[-8, -8]"
              type="error"></u-badge>
            <u-badge v-if="item.id == 5 && item.notice && item.dynamic_unread" :is-dot="true" :offset="[-8, -8]"
              type="error"></u-badge>
          </view>
          <view class="c-#515151 text-24 mt-1">{{ item.title }}</view>
        </view>
      </view>
    </view>
    <view v-if="societyNum > 1 && userStore.isLogin">
      <stacking-swiper :data="data" @refresh="refresh" />
    </view>
    <!-- 通用提示弹窗 -->
    <u-modal v-model="state.modalConfig.showTipModal" :show-title="false" border-radius="12" :show-confirm-button="false">
      <view class="slot-content">
        <view class="flex justify-center c-#333 text-32 font-bold">温馨提示</view>
        <view @click="state.modalConfig.showTipModal = false"
          class="absolute top-0 right-17 w-166 h-166 flex justify-end">
          <image class="mt-3 mr-2 w-22 h-22" src="/static/images/home/ic_delete.png" />
        </view>

        <view class="text-center c-#333 text-sm my-10">
          {{ state.modalConfig.desc }}
        </view>
        <view class="flex items-center justify-center">
          <view v-if="state.modalConfig.showCloseBtn" class="btn-save mx-3"
            @click="state.modalConfig.showTipModal = false">知道了</view>
          <view v-if="state.modalConfig.showCancelBtn" class="btn-save mx-3"
            @click="onCancelApply(state.modalConfig.clubId)">取消申请</view>
          <view v-if="state.modalConfig.showJumpBtn" class="btn-save mx-3"
            @click="onTipModalConfrim(state.modalConfig.jumpUrl)">{{ state.modalConfig.btnName }}
          </view>
          <view v-if="state.modalConfig.showEnterBtn" class="btn-save mx-3" @click="onEnter(state.modalConfig.enterUrl)">
            知道了
          </view>
        </view>
      </view>
    </u-modal>
  </view>
</template>

<script setup>
import { navigate, showToast } from "@/common/util/uni";
import { computed } from 'vue';
import { actionList, societyCreaterStatus, societyMemberStatus } from '@/common/constant/society.js'
import { postSocietyCancelApply } from '@/common/http/module/society.js'
import dayjs from 'dayjs'
import { useUserStore } from '@/store/user'

const emit = defineEmits(['refresh'])
const userStore = useUserStore()
const props = defineProps({
  data: {
    type: Array,
    default: () => []
  }
})

const state = reactive({
  modalConfig: {
    desc: '', // 提示内容
    showTipModal: false, // 提示弹窗
    showCloseBtn: false,
    showJumpBtn: false,
    btnName: '', // 按钮名称,
    jumpUrl: '',
    showEnterBtn: false,
    enterUrl: '',
    showCancelBtn: false, // 取消申请学社按钮
    clubId: '' // 学社id
  },
});

const userInfo = computed(() => userStore.userInfo)
// 学社数量
const societyNum = computed(() => props.data.length)

const societyTagLabel = computed(() => {
  const statusList = props.data.length == 1 && props.data[0].member_position == 3 ? societyCreaterStatus : societyMemberStatus
  const status = props.data.length == 1 && props.data[0].member_position == 3 ? props.data[0].club.status : props.data[0].audit_status
  return statusList.find(v => v.value == status)?.label ?? ''
})

const societyTagType = computed(() => {
  const statusList = props.data.length == 1 && props.data[0].member_position == 3 ? societyCreaterStatus : societyMemberStatus
  const status = props.data.length == 1 && props.data[0].member_position == 3 ? props.data[0].club.status : props.data[0].audit_status
  return statusList.find(v => v.value == status)?.type ?? ''
})

// 学社操作栏
const societyOptions = computed(() => {
  return actionList.filter(v => props.data.length == 1 && props.data[0].member_position >= v.auth)
})

// 社长vip剩余30天范围内
function onValidityRange(vip_validity) {
  // 获取距过期结束30天前时间
  const warmDate = dayjs(vip_validity).subtract(30, 'day')
  // 当前时间是否在剩余30天范围内
  const isValidityRange = dayjs().isAfter(warmDate)
  return isValidityRange
}

// 社长会员过期倒计时
function onCountDown(vip_validity) {
  // 获取过期时间和当前时间的差异
  const endTime = dayjs(vip_validity)
  const nowTime = dayjs(new Date())
  const days = endTime.diff(nowTime, 'day') + 1
  return days
}

// 进入学社
function enterSociety(url, club_id, item) {
  // 学社状态:0=审核中,1=正常,2=禁用,3=已驳回,4=已过期
  const clubStatus = item.club.status
  // 申请加入学社审核状态:0=申请中,1=已通过,2=已驳回
  const auditStatus = item.audit_status
  // 学社身份:0=成员,1=顾问,2=管理员,3=社长
  const isCreator = item.member_position
  // 社长快过期弹窗
  const isCreatorExpire = isCreator == 3 && onValidityRange(item.creator.vip_validity)
  // 距离过期时间
  const validityTime = onCountDown(item.creator.vip_validity)
  // 是否能进入学社
  const canEnterSociety = clubStatus == 1 && auditStatus == 1
  if (canEnterSociety) {
    if (isCreatorExpire && item.creator.identity != 1) {
      state.modalConfig = {
        showTipModal: true,
        desc: `您的【${item.club?.club_name}】会员权益还有${validityTime}天到期，过期后，将暂停使用学社权限，为了保证学社的正常使用，记得及时续费哦~`,
        showJumpBtn: true,
        btnName: '去续费',
        jumpUrl: '/package_user/pages/vip/add',
        showEnterBtn: true,
        enterUrl: `${url}&club_id=${club_id}`
      }
      return
    }
    navigate(`${url}&club_id=${club_id}`, true)
  } else {
    // 过期弹窗提醒
    if (clubStatus == 4) {
      const desc = isCreator ? '您的会员权益已经过期了，如若继续享用学社服务，要及时续费哦' : '此学社使用权益已过期，因此将暂停服务，具体情况可与社长联系'
      state.modalConfig = {
        showTipModal: true,
        desc,
        showCloseBtn: !isCreator,
        showJumpBtn: isCreator,
        btnName: '去续费',
        jumpUrl: '/package_user/pages/vip/add'
      }
    }
    // 审核弹窗提醒
    if (clubStatus == 0 || auditStatus == 0) {
      const desc = isCreator ? '您的创建学社申请还在审核中，审核结果会第一时间通过公众号以提醒的形式通知您~' : '您的加入学社申请还在审核中，审核结果会第一时间通过公众号以提醒的形式通知您~'
      state.modalConfig = {
        showTipModal: true,
        desc,
        showCloseBtn: true,
      }
    }
    // 驳回弹窗提醒
    if (clubStatus == 3 || auditStatus == 2) {
      const desc = isCreator ? '很抱歉，您的创建申请被驳回，请重新提交申请~' : '很抱歉，您的加入申请被驳回，请重新提交申请~'
      state.modalConfig = {
        showTipModal: true,
        desc,
        showCloseBtn: isCreator,
        showJumpBtn: true,
        btnName: isCreator ? '重新提交' : '去提交',
        jumpUrl: isCreator ? `/package_society/pages/society/add?club_id=${club_id}` : `/package_society/pages/society/detail?id=${item.club?.id}`,
        showCancelBtn: !isCreator,
        clubId: club_id
      }
    }
  }
}

// 创建学社
function onCreateSociety() {
  if (!userStore.isLogin) {
    navigate('/package_user/pages/common/login')
    return
  }
  // 企业身份:0=普通,1=顾问,2=客户经理
  const identity = userInfo.value.identity
  // 会员标识:0=非会员,1=VIP,2=黄金会员,3=铂金会员,4=钻石会员
  const vip_level = userInfo.value.vip_level
  // 会员/顾问且有剩余创建个数
  if (identity == 1 || vip_level > 0) {
    if (userInfo.value.club_number > 0) {
      navigate('/package_society/pages/society/add')
    } else {
      // 弹窗提示
      state.modalConfig = {
        showTipModal: true,
        desc: '您的创建学社个数已达上线',
        showCloseBtn: true
      }
    }
  } else {
    // 非会员弹窗提示
    state.modalConfig = {
      showTipModal: true,
      desc: '非常抱歉，给您造成不好的体验，【八零学社】为了保证学社质量，让外贸人有一个良好的学习圈子，仅对会员开放创建学社功能',
      showJumpBtn: true,
      btnName: '了解会员权益',
      jumpUrl: '/package_user/pages/vip/add'
    }
  }
}

function onEnter(url) {
  state.modalConfig.showTipModal = false
  navigate(url, true)
}

// 通用弹窗按钮事件
function onTipModalConfrim(jumpUrl) {
  navigate(jumpUrl)
  state.modalConfig.showTipModal = false
}

// 取消申请学社
function onCancelApply(club_id) {
  postSocietyCancelApply({ club_id }).then(() => {
    showToast('取消申请成功', 'none')
    state.modalConfig.showTipModal = false
    // 刷新列表
    refresh()
  })
}

// 刷新学社数据
function refresh() {
  emit('refresh')
}
</script>

<style lang="scss" scoped>
.shadow-card {
  box-shadow: -1.2246468525851679e-16px 2px 6px 0px rgba(206, 143, 12, 0.1);
}

.border-avatar {
  border: 2rpx solid #fff;
}

.slot-content {
  position: relative;
  padding: 24rpx 40rpx 40rpx;
}

.btn-save {
  width: 100%;
  height: 68rpx;
  line-height: 68rpx;
  text-align: center;
  color: #fff;
  font-size: 28rpx;
  border-radius: 10rpx;
  background-color: #F4AF22;
}
</style>
